package org.dreamwork.jasmine2.web.controls;

import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.events.IDisposeListener;
import org.dreamwork.jasmine2.web.IWebContainer;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.util.VirtualFile;
import org.dreamwork.util.NameValueCollection;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.engine.JasmineRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-9-3
 * Time: 14:11:32
 */
public class FileControl extends TextBox implements IDisposeListener{
    private VirtualFile[] files;

    private static final String ENC_TYPE_STATUS = "form.enctype.status";

    private static final Logger logger = LoggerFactory.getLogger (FileControl.class);

    @Override
    public void init () {
        super.init ();
        if (context == null) context = HttpContext.current ();
        Object enctypeSetted = context.getAttribute (ENC_TYPE_STATUS);
        if (enctypeSetted == null) {
            IWebContainer form = page.getPage ().getForm ();
            if (form != null) {
                form.setAttribute ("enctype", "multipart/form-data");
            }
            context.setAttribute (ENC_TYPE_STATUS, true);
        }
    }

    public FileControl () {
        setAttribute ("type", "file");
        addDisposeEvent (this);
    }

    public VirtualFile getVirtualFile () {
        return files == null || files.length == 0 ? null : files [0];
    }

    public VirtualFile[] getVirtualFiles () {
        return files;
    }

    @Override
    public void postbackData (NameValueCollection props) {
        HttpServletRequest req = HttpContext.current ().getRequest ();
        if (req instanceof JasmineRequest) {
            JasmineRequest request = (JasmineRequest) req;
            files = request.getVirtualFiles (id);
/*
            if (file != null && StringUtil.isEmpty (file.getName ())) {
                MimeType type = MimeTypeManager.getMimeTypeByName (file.getType ());
                if (type != null) {
                    String ext = type.getExt ();
                    file.setName (id + '.' + ext);
                } else
                    file.setName (id);
            }
*/
        }
    }

    public void onDispose (IWebControl sender) throws EventException {
        if (logger.isDebugEnabled ()) {
            logger.debug ("dispose FileControl[" + id + "], deleting TempFile!");
        }
        if (files != null) for (VirtualFile file : files){
            file.deleteTempFile ();
        }

        Object enctypeSetted = context.getAttribute (ENC_TYPE_STATUS);
        if (enctypeSetted != null) {
            context.removeAttribute (ENC_TYPE_STATUS);
        }
    }
}